import React, { useState } from 'react';
import request from 'umi-request';
import qs from 'qs';
import { Button, Icon, message } from 'antd';
import styles from './index.less';

const FileBtn = props => {
  const { fileId, fileName, clickType, titleNmae, download } = props;
  const [loading, setLoading] = useState(false);
  const [fileError, setFileError] = useState('');
  const handleViewFile = (id, name) => {
    setLoading(true);
    if (!fileName || fileName === '') {
      setFileError('文件名称不符！');
      setLoading(false);
      if (!titleNmae) {
        message.warning('文件名称不符！');
      }
      return;
    }
    const fileTypeArr = [
      'txt',
      'doc',
      'wps',
      'docx',
      'xls',
      'xlsx',
      'xlsm',
      'ppt',
      'pptx',
      'gif',
      'jpg',
      'png',
      'psd',
      'bmp',
      'pdf',
      'rar',
      'zip',
    ];
    const fileTypeCodeArr = [
      '3',
      '3',
      '3',
      '3',
      '3',
      '3',
      '3',
      '3',
      '3',
      '32',
      '32',
      '32',
      '39',
      '32',
      '34',
      '19',
      '19',
    ];
    const lastLen = name.lastIndexOf('.');
    const len = name.length;
    const suffix = name.substring(lastLen + 1, len);
    const fileTypeIndex = fileTypeArr.indexOf(suffix);
    if (fileTypeIndex > -1) {
      const convertType = fileTypeCodeArr[fileTypeIndex];
      const params = {
        downloadUrl: `${process.env.apiUrl}/api/v1/fileUpload/download?fileId=${id}`,
        convertType,
        isDelSrc: '1',
      };
      if (fileTypeArr[fileTypeIndex] === 'rar') {
        params.isRar5 = '1';
      }
      request('/docview/dcs/', {
        method: 'post',
        params,
      })
        .then(response => {
          // alert(`成功${JSON.stringify(response)}`);
          setLoading(false);
          if (response && response.result === 0) {
            const url = response.data[0];
            window.open(url);
          } else {
            setFileError(response.message);
            if (!titleNmae) {
              message.warning(response.message);
            }
          }
        })
        .catch(error => {
          // alert(`失败${JSON.stringify(error)}`);
          setLoading(false);
          setFileError('预览失败！');
          if (!titleNmae) {
            message.warning('预览失败！');
          }
        });
    } else {
      setFileError('文件格式不支持预览！');
      setLoading(false);
      if (!titleNmae) {
        message.warning('文件格式不支持预览！');
      }
    }
  };

  if (fileError !== '') {
    setTimeout(() => {
      setFileError('');
    }, 2000);
  }

  /* 文件下载 */
  function onclickDownload(fileId) {
    console.log(fileId);
    const params = {
      fileId,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/fileUpload/download?${exportQueryString}`);
  }

  return (
    <div className={styles['xh-file']}>
      <div className="xh-file-box">
        {titleNmae ? (
          <div className="xh-file-title">
            <Icon type="paper-clip" />
            &nbsp; &nbsp;
            <div onClick={() => clickType === 'textClick' && handleViewFile(fileId, fileName)}>
              {fileName}
            </div>
            &nbsp; &nbsp;
            {loading ? <Icon type="loading" /> : null}
            &nbsp; &nbsp;
            {download && <Icon type="download" onClick={() => onclickDownload(fileId)} />}
            <span className="xh-file-error">{fileError}</span>
          </div>
        ) : null}
        {clickType === 'btnClick' ? (
          <Button
            type="link"
            onClick={() => handleViewFile(fileId, fileName)}
            loading={!titleNmae && loading}
          >
            查看
          </Button>
        ) : null}
      </div>
    </div>
  );
};

export default FileBtn;
